package com.shenghui.enterprise.base.service.impl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shenghui.enterprise.base.entity.BaseDataDictionary;
import com.shenghui.enterprise.base.entity.BaseUser;
import com.shenghui.enterprise.utils.GeneralUtil;
import com.shenghui.enterprise.utils.UserUtil;
import com.shenghui.enterprise.vo.Result;
import com.shenghui.enterprise.base.entity.BaseDataDictionaryDetail;
import com.shenghui.enterprise.base.mapper.BaseDataDictionaryDetailMapper;
import com.shenghui.enterprise.base.mapper.BaseDataDictionaryMapper;
import com.shenghui.enterprise.base.service.IBaseDataDictionaryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 字典主表业务逻辑实现类
 * @Author houjh
 * @Email: happyxiaohou@gmail.com
 * @Date: 2020-06-01
 * @Copyright (c) 2020-2022 云南昇晖科技有限公司
 */
@Service
@Transactional
public class BaseDataDictionaryServiceImpl extends ServiceImpl<BaseDataDictionaryMapper, BaseDataDictionary> implements IBaseDataDictionaryService {

    @Autowired
    private BaseDataDictionaryMapper dataDictionaryMapper;
    @Autowired
    private BaseDataDictionaryDetailMapper dataDictionaryDetailMapper;
    @Autowired
    private UserUtil userUtil;

    /**
     * 获取数据字典列表
     * @param map
     * @return
     */
    @Override
    public Object getDataDictionaryList(Map map) {
        String parentId = "0";
        if(!StringUtils.isEmpty(map.get("id"))){
            parentId = map.get("id").toString();
        }
        List<Map<String, Object>> list = dataDictionaryMapper.selectMaps(new QueryWrapper<BaseDataDictionary>().lambda()
                .eq(BaseDataDictionary::getParentId, parentId).eq(BaseDataDictionary::getState,1)
                .orderByDesc(BaseDataDictionary::getOrderValue)
        );
        if(list != null && list.size() > 0){
            for(Map m : list){
                //判断是否有子集
                List<Map<String, Object>> result = dataDictionaryMapper.selectMaps(new QueryWrapper<BaseDataDictionary>().lambda()
                        .eq(BaseDataDictionary::getState,1).eq(BaseDataDictionary::getParentId, m.get("dataDictionaryId")));
                if(result != null && result.size() > 0){
                    m.put("isParent",true);
                } else {
                    m.put("isParent",false);
                }
                m.put("id",m.get("dataDictionaryId"));
                m.put("name",m.get("name"));
                m.put("orderValue",m.get("orderValue"));
                m.put("parentId",m.get("parentId"));
            }
            return list;
        }
        return null;
    }

    @Override
    public Result addDataDictionary(BaseDataDictionary dataDictionary) {
        int count = 0;
        BaseUser logBaseUser = userUtil.getLoginUser();
        String parentId = "0";
        if(GeneralUtil.isNull(dataDictionary.getParentId())) {
            dataDictionary.setParentId(parentId);
        }
        if (GeneralUtil.isNotNull(dataDictionary.getDataDictionaryId())) {    //修改
            //验证code是否重复
            count = dataDictionaryMapper.selectCount(new QueryWrapper<BaseDataDictionary>().lambda()
                    .eq(BaseDataDictionary::getCode, dataDictionary.getCode())
                    .ne(BaseDataDictionary::getDataDictionaryId, dataDictionary.getDataDictionaryId()));
            if(count > 0){
                return Result.error("字典Code码已存在!");
            }
            dataDictionary.setState(1);
            dataDictionaryMapper.updateById(dataDictionary);
        } else {    //新增
            //验证code是否重复
            count = dataDictionaryMapper.selectCount(new QueryWrapper<BaseDataDictionary>().lambda()
                    .eq(BaseDataDictionary::getCode, dataDictionary.getCode()));
            if(count > 0){
                return Result.error("字典Code码已存在!");
            }
            if (GeneralUtil.isNull(dataDictionary.getOrderValue())) {
                dataDictionary.setOrderValue(0);
            }
            dataDictionary.setState(1);
            dataDictionary.setCreateDate(LocalDateTime.now());
            if(GeneralUtil.isNotNull(logBaseUser)){
                dataDictionary.setCreateUserId(logBaseUser.getUserId());
            }
            dataDictionaryMapper.insert(dataDictionary);
        }
        return Result.ok( "字典添加成功", dataDictionary);
    }

    /**
     * 根据ID查询回显记录
     * @param id
     * @return
     */
    @Override
    public Result getDataDictionaryById(String id) {
        if(GeneralUtil.isNull(id)){
            return Result.error("必需参数【id】不能为空!");
        }
        Map<String,Object> result = dataDictionaryMapper.getDictionaryById(id);
        if(result != null && result.size() > 0){
            return Result.ok("查询成功", result);
        }
        return Result.error("未查询到对应的记录信息!");
    }

    /**
     * 删除数据字典信息
     * @param id
     * @return
     */
    @Override
    public Result deleteDataDictionary(String id) {
        if (StringUtils.isEmpty(id)) {
            return Result.error("必需参数【id】不能为空!");
        }
        //验证是否还存在子级
        List<BaseDataDictionary> lists = dataDictionaryMapper.selectList(new QueryWrapper<BaseDataDictionary>().lambda()
                .eq(BaseDataDictionary::getParentId, id).eq(BaseDataDictionary::getState, 1));
        if(lists != null && lists.size() > 0){
            return Result.error("该节点下还存在子级，不能删除!");
        }
        //验证是否存在详情
        int count = dataDictionaryDetailMapper.selectCount(new QueryWrapper<BaseDataDictionaryDetail>().lambda()
                .eq(BaseDataDictionaryDetail::getDataDictionaryId, id).eq(BaseDataDictionaryDetail::getState,1));
        if(count > 0){
            return Result.error("该字典下还存在详情信息，不能删除!");
        }
        //删除字典信息
        BaseDataDictionary baseDataDictionary = dataDictionaryMapper.selectById(id);
        baseDataDictionary.setState(0);
        dataDictionaryMapper.updateById(baseDataDictionary);
        return Result.ok("字典删除成功!");
    }


    @Override
    public List<Map<String, Object>> getDicDetailByCode(String iCode, String pCode) {
        Map m = dataDictionaryMapper.getDicDetailByCode(pCode, iCode);
        if (m != null) {
            List<BaseDataDictionary> baseDatadictionaries = dataDictionaryMapper.selectList(new QueryWrapper<BaseDataDictionary>()
                    .eq("parent_id", m.get("dataDictionaryId"))
                    .eq("state", 1));

            QueryWrapper query = new QueryWrapper<BaseDataDictionaryDetail>();
            query.select("name", "remark", "data_dictionary_id", "code");
            query.eq("data_dictionary_id", m.get("dataDictionaryId"));
            query.eq("state", 1);
            query.orderBy(true, true, "order_value");
            List<Map<String, Object>> detail = dataDictionaryDetailMapper.selectMaps(query);

            if (baseDatadictionaries.size() > 0) {
                for (int i = 0; i < baseDatadictionaries.size(); i++) {
                    QueryWrapper queryWrapper = new QueryWrapper<BaseDataDictionaryDetail>();
                    queryWrapper.select("name", "remark", "data_dictionary_id", "code");
                    queryWrapper.eq("data_dictionary_id", baseDatadictionaries.get(i).getDataDictionaryId());
                    queryWrapper.eq("state", 1);
                    queryWrapper.orderBy(true, true, "order_value");
                    List<Map<String, Object>> detailChids = dataDictionaryDetailMapper.selectMaps(queryWrapper);
                    for (Map<String, Object> map : detailChids) {
                        detail.add(map);
                    }
                }
            }
            return detail;
        }
        return null;
    }

    @Override
    public List<Map> getAllDataListByCode(String code) {
        List<Map> list = dataDictionaryMapper.getAllDataListByCode(code);
        return list;
    }

    @Override
    public Object getDataDictionaryDetailListByCode(String code) {
        try {
            Map<String, Object> result = new HashMap<String, Object>();
            if (GeneralUtil.isNotNull(code)) {
                JSONArray array = JSONObject.parseArray(code);
                if (!GeneralUtil.isNull(array) && array.size() > 0) {
                    for (int i = 0; i < array.size(); i++){
                        Map map = (Map) array.get(i);
                        if (GeneralUtil.isNotNull(map) && GeneralUtil.isNotNull(map.get("code"))) {
                            List<Map> maps = dataDictionaryMapper.getDataDictionaryDetailListByCode(map.get("code").toString());
                            result.put(map.get("id").toString(), maps);
                        }
                    }
                }
            }
            return Result.ok( "字典查询成功", result);
        } catch (Exception e){
            e.printStackTrace();
            return Result.error("字典查询失败");
        }
    }

    /**
     * 根据父级code查询子集以及子集详细
     * @return
     */
    @Override
    public Result getDataDictionaryTreeListByCode(String code) {
        BaseDataDictionary baseDataDictionary = dataDictionaryMapper.selectOne(new QueryWrapper<BaseDataDictionary>().lambda()
                .eq(BaseDataDictionary::getCode, code)
                .eq(BaseDataDictionary::getState, 1)
                .orderByDesc(BaseDataDictionary::getOrderValue)
        );
        List<Map<String, Object>> list = new ArrayList<>();
        if(GeneralUtil.isNotNull(baseDataDictionary)){
            //判断是否有子集
            QueryWrapper query = new QueryWrapper<BaseDataDictionary>();
            query.select("name", "remark", "data_dictionary_id", "code");
            query.eq("parent_id", baseDataDictionary.getDataDictionaryId());
            query.eq("state", 0);
            query.orderByDesc("order_value");
            list = dataDictionaryMapper.selectMaps(query);
            if(list != null && list.size() > 0){
                // 查询子集字典详情
                for (int i = 0; i < list.size(); i++) {
                    QueryWrapper queryWrapper = new QueryWrapper<BaseDataDictionaryDetail>();
                    queryWrapper.select("name", "remark", "data_dictionary_id", "code");
                    queryWrapper.eq("data_dictionary_id", list.get(i).get("dataDictionaryId"));
                    queryWrapper.eq("state", 1);
                    queryWrapper.orderBy(true, true, "order_value");
                    List<Map<String, Object>> detailChids = dataDictionaryDetailMapper.selectMaps(queryWrapper);
                    list.get(i).put("detailChids", detailChids);
                }
            } else {
            }
        }
        return Result.ok("", list);
    }

}
